using System;
using System.Collections.Generic;
using System.Globalization;
using System.Net;
using System.Text;
using System.Xml;

namespace iPhOwa.Exchange.WebDav.Methods
{
	/// <summary>
	/// Implements the PROPPATCH WebDAV method.
	/// </summary>
	internal sealed class PropPatch : Method
	{
		private readonly IDictionary<string, object> properties;

		public PropPatch(Uri path, OwaSession session, IDictionary<string, object> properties) : base(path, session)
		{
			this.properties = properties;
		}

		/// <summary>
		/// The name of the method
		/// </summary>
		public override string Name
		{
			get { return "PROPPATCH"; }
		}

		/// <summary>
		/// Build the command XML.
		/// </summary>
		protected override string BuildCommand()
		{
			using(EncodingStringWriter s = new EncodingStringWriter(Encoding.UTF8, CultureInfo.InvariantCulture))
			{
				using(XmlTextWriter x = new XmlTextWriter(s))
				{
					x.Formatting = Formatting.Indented;
					x.WriteStartDocument();
					x.WriteStartElement("propertyupdate", "DAV:");
					x.WriteStartElement("set", "DAV:");
					x.WriteStartElement("prop", "DAV:");

					foreach(KeyValuePair<string, object> prop in properties)
					{
						KeyValuePair<string, string> p = ParseProperty(prop.Key);

						x.WriteElementString(p.Value, p.Key, prop.Value.ToString());
					}

					x.WriteEndElement();
					x.WriteEndElement();
					x.WriteEndDocument();
				}

				StringBuilder sb = s.GetStringBuilder();

				return sb.ToString();
			}
		}

		/// <summary>
		/// Add method specific headers to request.
		/// </summary>
		protected override void AddHeaders(HttpWebRequest request)
		{
			request.Headers.Add("Translate", "F");
		}

		/// <summary>
		/// Run the call.
		/// </summary>
		public void Run()
		{
			Execute();
		}
	}
}